const app = getApp();
import { baseApiUrl } from "./config";
const whiteList = ['api/login/wechat'];
export default class Request {
  postRequest(url, data) {
    return new Promise((resolve, reject) => {
      const header = {};
      if (whiteList.includes(url)) { } else {
        let token = app.globalData?.token ?? "";
        header["ApiToken"] = token;
      };
      wx.request({
        url: `${baseApiUrl}/${url}`,
        method: 'POST',
        data: { ...data },
        header: header,
        success: (res) => {
          res = res.data;
          let { code, data, msg } = res;
          if (code != 0) {
            if (code == -10 || code == -999) {
              app.globalData.token = "";
              wx.setStorageSync('token', "");
              wx.showToast({ title: "正在重新登录", icon: 'none' })
              wx.switchTab({
                url: '/pages/index/index'
              })
              // setTimeout(() => {
              //   wx.switchTab({
              //     url: '/pages/index/index'
              //   })
              // }, 2000);
              reject(res)
            } else {
              wx.showToast({ title: msg, icon: 'none' })
              reject(res)
            }
          } else {
            resolve(data)
          };
        },
        fail: err => reject(err)
      })
    })
  }
  uploadRequest(url, filePath) {
    return new Promise((resolve, reject) => {
      let token = app.globalData?.token ?? "";
      wx.uploadFile({
        url: `${baseApiUrl}/${url}`,
        filePath: filePath,
        name: 'file',
        header: { ApiToken: token },
        success: (res) => {
          res = JSON.parse(res.data);
          let { code, data, msg } = res;
          code != 0 ? wx.showToast({ title: msg, icon: 'none' }) : resolve(data);
        },
        fail: err => reject(err)
      })
    })
  }
  paymentRequest(data) {
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        ...data,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })
  }
}